﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VietThuongLMS.ViewModels;
using System.Web.Mvc;
using System.Data.Entity;
using System.Globalization;
using System.Data.Objects.SqlClient;
using VietThuongLMS.Utils;

/**
 * <Jason>
 * <Date: 20131114>
 * 
 */
namespace VietThuongLMS.Services
{
    public class HocVienService
    {

        public List<HocVien> GetHocVienList()
        {
            try
            {
                using (LMSDataEntities context = new LMSDataEntities())
                {
                    List<HocVien> list = context.HocViens.Include("LoaiTaiKhoan").Where(m => m.TaiKhoan.MaLoaiTaiKhoan == Utils.Constant.ACCOUNT_ROLE_STUDENT).ToList();
                    return list;
                }
            }
            catch (Exception ex)
            {
                DCS.ComLib.File.Log.Write("HocVienServices::GetHocVienList", ex.StackTrace, ex.Message);
                return null;
            }
        }

        public static HocVienViewModel GetHocVienList(int pageNum, int pageIndex)
        {
            try
            {
                using (LMSDataEntities context = new LMSDataEntities())
                {
                    //List<HocVien> list = context.HocViens.Include("Role").OrderBy(m => m.signupDate).Skip(pageNum * (pageIndex - 1)).Take(pageNum).ToList();
                    //List<HocVien> list = context.HocViens.Include("TaiKhoan").Where(m.TaiKhoan.MaLoaiTaiKhoan == Utils.Constant.ACCOUNT_ROLE_STUDENT).OrderBy(m => m.TaiKhoan.NgayDangKy).Skip(pageNum * (pageIndex - 1)).Take(pageNum).ToList();
                    List<HocVien> list = context.HocViens.Include("TaiKhoan").Where(w => w.Deleted != -1 || w.Deleted == null)
                        .OrderBy(m => m.TaiKhoan.NgayDangKy).Skip(pageNum * (pageIndex - 1)).Take(pageNum).ToList();
                    foreach (HocVien hv in list)
                    {
                        hv.TaiKhoan.LoaiTaiKhoanReference.Load();
                    }
                    int total = context.HocViens.Include("TaiKhoan").Where(w => w.Deleted != -1 || w.Deleted == null).Count();
                    return new HocVienViewModel(list, total);
                }
            }
            catch (Exception ex)
            {
                DCS.ComLib.File.Log.Write("HocVienServices::GetHocVienList", ex.StackTrace, ex.Message);
                return new HocVienViewModel();
            }
        }

        public static HocVienViewModel GetHocVienList(int pageNum, int pageIndex, string userName)
        {
            try
            {
                using (LMSDataEntities context = new LMSDataEntities())
                {
                    TaiKhoan tk = context.TaiKhoans.FirstOrDefault(t => t.MaTaiKhoan == userName);
                    if (tk != null)
                    {
                        NhanVien nhanVien = context.NhanViens.FirstOrDefault(n => n.MaTaiKhoan == tk.ID);
                        //List<HocVien> list = context.HocViens.Include("Role").OrderBy(m => m.signupDate).Skip(pageNum * (pageIndex - 1)).Take(pageNum).ToList();
                        //List<HocVien> list = context.HocViens.Include("TaiKhoan").Where(m.TaiKhoan.MaLoaiTaiKhoan == Utils.Constant.ACCOUNT_ROLE_STUDENT).OrderBy(m => m.TaiKhoan.NgayDangKy).Skip(pageNum * (pageIndex - 1)).Take(pageNum).ToList();
                        List<HocVien> list = context.HocViens.Include("TaiKhoan").Where(w => w.Deleted != -1)
                            .OrderBy(m => m.TaiKhoan.NgayDangKy).Skip(pageNum * (pageIndex - 1)).Take(pageNum).ToList();
                        for (int i = 0; i < list.Count; i++)
                        {
                            HocVien_Lop hvl = context.HocVien_Lop.FirstOrDefault(w => w.MaHocVien == list[i].ID);
                            if (hvl == null)
                            {
                                list.Remove(list[i]);
                                break;
                            }
                            if (hvl.MaChiNhanh != nhanVien.MaChiNhanh)
                                list.Remove(list[i]);
                        }
                        foreach (HocVien hv in list)
                        {
                            hv.TaiKhoan.LoaiTaiKhoanReference.Load();
                        }
                        int total = context.HocViens.Include("TaiKhoan").Where(w => w.Deleted != -1).Count();
                        return new HocVienViewModel(list, total);
                    }
                    return new HocVienViewModel(new List<HocVien>(), 0);
                }
            }
            catch (Exception ex)
            {
                DCS.ComLib.File.Log.Write("HocVienServices::GetHocVienList", ex.StackTrace, ex.Message);
                return new HocVienViewModel();
            }
        }

        public static bool InsertHocVien(HocVien comp)
        {
            try
            {
                using (LMSDataEntities context = new LMSDataEntities())
                {
                    context.AddToHocViens(comp);
                    context.SaveChanges();
                    return true;
                }
            }
            catch (Exception ex)
            {
                DCS.ComLib.File.Log.Write("HocVienServices::InsertHocVien", ex.StackTrace, ex.Message);
                return false;
            }
        }

        /// <summary>
        /// Them hoc vien
        /// Author: NHDuc
        /// Created date: 1/12/2013
        /// </summary>
        /// <param name="comp">doi tuong thuoc lop HocVien</param>
        /// <returns>ID cua hoc vien sau khi them / tra ve -1 neu false</returns>
        public static int InsertHocVienReturn(HocVien comp)
        {
            try
            {
                using (LMSDataEntities context = new LMSDataEntities())
                {
                    context.AddToHocViens(comp);
                    context.SaveChanges();
                    return comp.ID;
                }
            }
            catch (Exception ex)
            {
                DCS.ComLib.File.Log.Write("HocVienServices::InsertHocVienReturn", ex.StackTrace, ex.Message);
                return -1;
            }
        }

        /// <summary>
        /// Lay ma hoc vien theo ma tai khoan
        /// Author: NHDuc
        /// Created date: 14/12/2013
        /// </summary>
        /// <param name="comp">id cua tai khoan</param>
        /// <returns>ID cua hoc vien / tra ve -1 neu false</returns>
        public static int GetHocVienIdByTaiKhoanId(int id)
        {
            LMSDataEntities context = null;
            try
            {
                context = new LMSDataEntities();
                var hv = context.HocViens.Join(context.TaiKhoans, h => h.MaTaiKhoan, t => t.ID, (h, t) => new { h, t })
                    .Where(t => t.t.ID == id)    
                    .FirstOrDefault();
                return (hv != null) ? hv.h.ID : -1;
            }
            catch (Exception ex)
            {
                DCS.ComLib.File.Log.Write("HocVienServices::GetHocVienIdByTaiKhoanId", ex.StackTrace, ex.Message);
                return -1;
            }
            finally
            {
                context.Dispose();
            }
        }

        public static bool DeleteHocVien(int maHocVien)
        {
            try
            {
                using (LMSDataEntities context = new LMSDataEntities())
                {
                    HocVien obj = context.HocViens.Where(c => c.ID == maHocVien).FirstOrDefault();
                    if (obj != null)
                    {
                        //context.HocViens.DeleteObject(obj);
                        obj.Deleted = -1;
                        context.SaveChanges();
                        return true;
                    }
                    return false;
                }
            }
            catch (Exception ex)
            {
                DCS.ComLib.File.Log.Write("HocVienServices::DeleteHocVien", ex.StackTrace, ex.Message);
                return false;
            }
        }

        public static HocVien GetHocVienById(int id)
        {
            try
            {
                using (LMSDataEntities context = new LMSDataEntities())
                {
                    return context.HocViens.Include("TaiKhoan").Where(c => c.ID == id).FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                DCS.ComLib.File.Log.Write("HocVientServices::GetHocVienById", ex.StackTrace, ex.Message);
                return null;
            }
        }

        public static bool Edit(HocVien newModel)
        {
            try
            {
                using (LMSDataEntities context = new LMSDataEntities())
                {
                    HocVien model = context.HocViens.Where(c => c.ID == newModel.ID).FirstOrDefault();
                    //Trong đây, sau khi lấy xong ra 1 học viên từ db có id = id của newModel.

                    if (model != null)
                    {
                        //comp.userid = newComp.userid;
                        model.ID = newModel.ID;
                        model.MoiQuanHe = newModel.MoiQuanHe;
                        model.HoTenLienHe = newModel.HoTenLienHe;
                        model.DiaChiNguoiLienHe = newModel.DiaChiNguoiLienHe;
                        model.DienThoaiNguoiLienHe = newModel.DienThoaiNguoiLienHe;
                        model.EmailNguoiLienHe = newModel.EmailNguoiLienHe;
                        model.Deleted = newModel.Deleted;

                        //Nếu ko cập nhật lại mấy cái đó, thì dù ben ngoài mày có nhạp cái lồng gì
                        //Thì nó cũng lấy giá trị select được từ DB để trả lại .
                        context.SaveChanges();
                        return true;
                    }
                    return false;
                }
            }
            catch (Exception ex)
            {
                DCS.ComLib.File.Log.Write("HocVienServices::Edit", ex.StackTrace, ex.Message);
                return false; 
            }
        }

        //Added by Kha
        public static HocVienViewModel DanhSachHocVienMoi(int m, int y,int pageNum, int pageIndex)
        {
            var context = new LMSDataEntities();
            try
            {
                var lhv = (from hv_l in context.HocVien_Lop where hv_l.NgayDangKy.Value.Month==m && hv_l.NgayDangKy.Value.Year==y && hv_l.DongHocPhi==1 group hv_l by new {hv_l.MaHocVien} into hv_lgrp
                           where hv_lgrp.Count() <= 1
                           select new HocVienMoRongModel
                           {
                               TK = (from hv in context.HocViens
                                     where hv.ID == hv_lgrp.Key.MaHocVien
                                     select hv.TaiKhoan).FirstOrDefault() ,
                               NgayDangKy = (from hv_l in context.HocVien_Lop
                                     where hv_l.ID == hv_lgrp.Key.MaHocVien
                                     select hv_l.NgayDangKy.Value).FirstOrDefault()
                           })                                                                                
                    .OrderBy(p => p.TK.HoTen).Skip(pageNum * (pageIndex - 1)).Take(pageNum).ToList();
                int total = (from hv_l in context.HocVien_Lop
                             where hv_l.DongHocPhi == 1
                             group hv_l by new { hv_l.MaHocVien } into hv_lgrp
                             where hv_lgrp.Count() <= 1 
                             select hv_lgrp).ToList().Count;
                HocVienViewModel hvvm = new HocVienViewModel(lhv, total);
                return hvvm;
            }
            catch (Exception ex)
            {
                DCS.ComLib.File.Log.Write("HocVienServices::DanhSachHocVienMoi", ex.StackTrace, ex.Message);
                throw ex;
            }
            finally
            {
                context.Dispose();
            }
        }
        public static HocVienViewModel DanhSachHocVienNghiHoanToan(int m, int y,int pageNum, int pageIndex)
        {
            var context = new LMSDataEntities();
            try
            {
                string dr = "01/" + m.ToString() + "/" + y.ToString();
                DateTime dt = DateTime.Parse(dr, new CultureInfo("FR-fr", true));
                dt.AddDays(-4000);
                var lhv = (from hv_l in context.HocVien_Lop
                           where hv_l.NgayDangKy.Value.CompareTo(dt)<=0
                           group hv_l by new {hv_l.MaHocVien} into hv_lgrp select new HocVienMoRongModel { TK = (from tk in context.TaiKhoans
                                                                                                                 from hv in context.HocViens
                                                                                                                 where hv.ID==hv_lgrp.Key.MaHocVien
                                                                                                                 && hv.MaTaiKhoan ==tk.ID
                                                                                                                 select tk).FirstOrDefault(),
                           NgayDangKy = (from hv_l in context.HocVien_Lop where hv_l.MaHocVien == hv_lgrp.Key.MaHocVien
                                         select hv_l.NgayDangKy.Value).OrderBy(p=>p).FirstOrDefault()}).
                                         OrderBy(t => t.NgayDangKy).Skip(pageNum * (pageIndex - 1)).Take(pageNum).ToList();
                int total = (from hv_l in context.HocVien_Lop
                             where hv_l.NgayDangKy.Value.CompareTo(dt) <= 0
                           group hv_l by new {hv_l.MaHocVien} into hv_lgrp select hv_lgrp).Count();
                HocVienViewModel hvvm = new HocVienViewModel(lhv, total);
                return hvvm;
            }
            catch (Exception ex)
            {
                DCS.ComLib.File.Log.Write("HocVienServices::DanhSachHocVienNghiHoanToan", ex.StackTrace, ex.Message);
                throw ex;
            }
            finally
            {
                context.Dispose();
            }
        }
        //End addition

        /// <summary>
        /// Lay thong tin hoc vien va danh sach lop ma hoc vien do da dang ky hoc
        /// </summary>
        /// <param name="pageNum"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public static ThongTinHocVienModel GetThongTinHocVien(string userName)
        {
            LMSDataEntities context = null;
            try
            {
                context = new LMSDataEntities();
                //lay thong tin hoc vien
                ThongTinHocVienModel hocVien = context.HocViens
                    .Join(context.TaiKhoans, hv => hv.MaTaiKhoan, t => t.ID, (s, t) => new { HocVien = s, TaiKhoan = t })
                    .Where(h => h.TaiKhoan.MaTaiKhoan == userName)
                    .Select(a => new ThongTinHocVienModel
                    {
                        taiKhoanModel = a.TaiKhoan,
                        hocVienModel = a.HocVien
                    }).FirstOrDefault();

                ////lay danh sach lop
                //List<HocVien_Lop> list = context.HocVien_Lop.Where(h => h.MaHocVien == hocVien.hocVienModel.ID).ToList();
                //if (list != null && list.Count > 0)
                //{

                //}
                return hocVien;
            }
            catch (Exception ex)
            {
                DCS.ComLib.File.Log.Write("HocVienService::GetThongTinHocVien", ex.StackTrace, ex.Message);
                return new ThongTinHocVienModel();
            }
            finally
            {
                context.Dispose();
            }
        }
    }
}
